package com.jarvan.utils;

import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Arrays;

@Slf4j
public class PinyinUtil {

    public static String toPinyu(String chinese){
        char[] clChar = chinese.trim().toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V);

        try {
            for (char cl_char: clChar){
                if (String.valueOf(cl_char).matches("[\\u4e00-\\u9fa5]+")){
                    pinyin.append(PinyinHelper.toHanyuPinyinStringArray(cl_char, defaultFormat)[0]);
                } else {
                    pinyin.append(cl_char);
                }
            }
        }catch (BadHanyuPinyinOutputFormatCombination e){
            log.error("[拼音转换]  字符无法转换为拼音");
        }
        return pinyin.toString();
    }
    
    public static String getFirstUp(String chinese, HanyuPinyinCaseType caseType){
        return getFirstLetter(chinese, caseType);
    }

    private static String getFirstLetter(String chinese, HanyuPinyinCaseType caseType) {
        char[] clChars = chinese.trim().toCharArray();
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(caseType);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        for (char cl_char: clChars){
            String str = String.valueOf(cl_char);
            if (str.matches("[\u4e00-\u9fa5]+")){
                pinyin.append(Arrays.toString(PinyinHelper.toHanyuPinyinStringArray(cl_char)));
            } else if (str.matches("[0-9]+")){
                pinyin.append(cl_char);
            } else {
                pinyin.append(cl_char);
            }
        }
        return pinyin.toString();
    }
}
